package com.jds.clickhouse.web.service.impl.portray;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jds.clickhouse.web.service.portray.CustomerWechatDetailService;
import com.jds.clickhouse.web.service.portray.ScvQyExternalUserService;
import com.jds.clickhouse.web.service.portray.ScvSensorTenAggregationService;
import com.jds.clickhouse.web.service.portray.ScvSourceQyQyUsersService;
import com.jds.clickhouse.web.service.sys.SysUserService;
import com.jds.link4sales.common.result.ResultJson;
import com.jds.link4sales.common.utils.AesUtils;
import com.jds.link4sales.model.dto.ActionsDto;
import com.jds.link4sales.model.entity.portray.*;
import com.jds.link4sales.model.entity.sys.SysUser;
import com.jds.link4sales.model.mapper.portray.ScvSensorTenAggregationMapper;
import com.jds.link4sales.model.mapper.portray.ScvSensorTenAggregationV2Mapper;
import com.jds.link4sales.model.mapper.portray.ScvSourceGpSperoCommentServiceLiveCommentMapper;
import com.jds.link4sales.model.vo.ScvSensorTenAggregationResultVo;
import com.jds.link4sales.model.vo.ScvSensorTenAggregationV2Vo;
import com.jds.link4sales.model.vo.ScvWxSensorTenAggregationV2Vo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 神策埋点10分钟聚合数据 服务实现类
 * </p>
 *
 * @author zhixiang.peng
 * @since 2021-01-07
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class ScvSensorTenAggregationServiceImpl extends ServiceImpl<ScvSensorTenAggregationMapper, ScvSensorTenAggregation> implements ScvSensorTenAggregationService {

    private final ScvSensorTenAggregationMapper scvSensorTenAggregationMapper;

    private final ScvSensorTenAggregationV2Mapper scvSensorTenAggregationV2Mapper;

    private final ScvSourceGpSperoCommentServiceLiveCommentMapper scvSourceGpSperoCommentServiceLiveCommentMapper;

    private final ScvQyExternalUserService scvQyExternalUserService;

    private final ScvSourceQyQyUsersService scvSourceQyQyUsersService;

    private final CustomerWechatDetailService customerWechatDetailService;

    private final SysUserService sysUserService;

    @Value("${aes.key}")
    private String secretKey;

    @Override
    public ResultJson getGpLiveInfo(ActionsDto actionsDto) {

        //获取按照时间倒序拍好顺序的房间
        List<ScvSensorTenAggregation> list = scvSensorTenAggregationMapper.getGpLiveList(actionsDto);

        list.forEach(item -> {
            //查询每个房间的前3条进入时间
            List<ScvSensorTenAggregation> top3list=null;
            if(item.getRoomid()!=null){
                top3list = scvSensorTenAggregationMapper.selectList(new LambdaQueryWrapper<ScvSensorTenAggregation>().eq(ScvSensorTenAggregation::getOneid, item.getOneid()).eq(ScvSensorTenAggregation::getRoomid, item.getRoomid()).eq(ScvSensorTenAggregation::getTitle,item.getTitle()).orderByDesc(ScvSensorTenAggregation::getIntoRoomTime).last("limit 3"));
            }else{
                top3list = scvSensorTenAggregationMapper.selectList(new LambdaQueryWrapper<ScvSensorTenAggregation>().isNull(ScvSensorTenAggregation::getRoomid).eq(ScvSensorTenAggregation::getOneid, item.getOneid()).eq(ScvSensorTenAggregation::getTitle,item.getTitle()).orderByDesc(ScvSensorTenAggregation::getIntoRoomTime).last("limit 3"));
            }
            item.setDetail(top3list);

            //查询每个房间的前3条评论
//            List<ScvSourceGpSperoCommentServiceLiveComment> top3CommentList = scvSourceGpSperoCommentServiceLiveCommentMapper.selectList(new LambdaQueryWrapper<ScvSourceGpSperoCommentServiceLiveComment>().eq(ScvSourceGpSperoCommentServiceLiveComment::getOneId, item.getOneid()).eq(ScvSourceGpSperoCommentServiceLiveComment::getRoomId, item.getRoomid()).eq(ScvSourceGpSperoCommentServiceLiveComment::getStatus,"审核通过").orderByDesc(ScvSourceGpSperoCommentServiceLiveComment::getCreatedAt).last("limit 3"));
//            item.setCommentDetail(top3CommentList);
        });
        return ResultJson.success(new PageInfo<>(list));
    }



    @Override
    public ResultJson<Object> getList(ActionsDto actionsDto) {
        PageHelper.startPage(actionsDto.getPageNum(), actionsDto.getPageSize());
        LambdaQueryWrapper<ScvSensorTenAggregation> scvSensorTenAggregationLambdaQueryWrapper = new LambdaQueryWrapper<ScvSensorTenAggregation>()
                .eq(ScvSensorTenAggregation::getTitle, actionsDto.getTitle())
                .orderByDesc(ScvSensorTenAggregation::getIntoRoomTime);
        if(actionsDto.getRoomId()!=null){
            scvSensorTenAggregationLambdaQueryWrapper.eq(ScvSensorTenAggregation::getRoomid,actionsDto.getRoomId());
        }else{
            scvSensorTenAggregationLambdaQueryWrapper.isNull(ScvSensorTenAggregation::getRoomid);
        }
        List<ScvSensorTenAggregation> scvSensorTenAggregations = scvSensorTenAggregationMapper.selectList(scvSensorTenAggregationLambdaQueryWrapper);
        return ResultJson.success(scvSensorTenAggregations);
    }

    @Override
    public ResultJson<Object> getCommentList(ActionsDto actionsDto) {
        PageHelper.startPage(actionsDto.getPageNum(), actionsDto.getPageSize());
        List<ScvSourceGpSperoCommentServiceLiveComment> scvSourceGpSperoCommentServiceLiveComments = scvSourceGpSperoCommentServiceLiveCommentMapper.selectList(new LambdaQueryWrapper<ScvSourceGpSperoCommentServiceLiveComment>().eq(ScvSourceGpSperoCommentServiceLiveComment::getOneId, actionsDto.getOneId()).eq(ScvSourceGpSperoCommentServiceLiveComment::getRoomId, actionsDto.getRoomId()).eq(ScvSourceGpSperoCommentServiceLiveComment::getStatus,"审核通过").orderByDesc(ScvSourceGpSperoCommentServiceLiveComment::getCreatedAt));
        return ResultJson.success(scvSourceGpSperoCommentServiceLiveComments);
    }

    @Override
    public ResultJson<Object> getActionDataList(ActionsDto actionsDto) {
        PageHelper.startPage(actionsDto.getPageNum(), actionsDto.getPageSize());
        LambdaQueryWrapper<ScvSensorTenAggregationV2> scvSensorTenAggregationLambdaQueryWrapper = new LambdaQueryWrapper<ScvSensorTenAggregationV2>()
                .eq(ScvSensorTenAggregationV2::getTitleId, actionsDto.getTitleId()).eq(ScvSensorTenAggregationV2::getOneId,actionsDto.getOneId())
                .orderByDesc(ScvSensorTenAggregationV2::getEventTime);
        List<ScvSensorTenAggregationV2> scvSensorTenAggregations = scvSensorTenAggregationV2Mapper.selectList(scvSensorTenAggregationLambdaQueryWrapper);
        return ResultJson.success(scvSensorTenAggregations);
    }
    /**
     * 新版本产品对应的查询逻辑
     *
     * @param
     * @return
     */
    @Override
    public ResultJson getGpLiveInfoV2(ActionsDto actionsDto) {

        //获取按照时间倒序拍好顺序的房间
        List<ScvSensorTenAggregationResultVo> list = scvSensorTenAggregationV2Mapper.getGpLiveList(actionsDto);
        list.forEach(item -> {
            //查询每个房间的前10条事件行为
            List<ScvSensorTenAggregationV2> top10list;
            if (item.getRoomId() != null) {
                top10list = scvSensorTenAggregationV2Mapper.selectList(new LambdaQueryWrapper<ScvSensorTenAggregationV2>().eq(ScvSensorTenAggregationV2::getOneId, item.getOneId()).eq(ScvSensorTenAggregationV2::getRoomId, item.getRoomId()).eq(ScvSensorTenAggregationV2::getTitleId, item.getTitleId()).orderByDesc(ScvSensorTenAggregationV2::getEventTime).last("limit 10"));
            } else {
                top10list = scvSensorTenAggregationV2Mapper.selectList(new LambdaQueryWrapper<ScvSensorTenAggregationV2>().isNull(ScvSensorTenAggregationV2::getRoomId).eq(ScvSensorTenAggregationV2::getOneId, item.getOneId()).eq(ScvSensorTenAggregationV2::getTitleId, item.getTitleId()).orderByDesc(ScvSensorTenAggregationV2::getEventTime).last("limit 10"));
            }
            item.setDetail(top10list);
        });

        return ResultJson.success(new PageInfo<>(list));
    }

    @Override
    public ResultJson getWebWeChatGpLiveInfo(ActionsDto actionsDto) {
        PageHelper.startPage(actionsDto.getPageNum(), actionsDto.getPageSize());
        List<ScvSensorTenAggregationV2Vo> scvSensorTenAggregationV2Vos = scvSensorTenAggregationMapper.getWebWeChatGpLiveList(actionsDto);
        if (!CollectionUtils.isEmpty(scvSensorTenAggregationV2Vos)) {
            //外部联系人id
            List<Integer> collect = scvSensorTenAggregationV2Vos.stream().map(ScvSensorTenAggregationV2Vo::getExId)
                    .collect(Collectors.toList());
            List<ScvQyExternalUser> scvQyExternalUsers = scvQyExternalUserService.listByExternalId(collect);
            //外部联系人属性赋值
            if (!CollectionUtils.isEmpty(scvQyExternalUsers)) {
                scvSensorTenAggregationV2Vos.forEach(scvSensorTenAggregationV2Vo -> {
                    scvQyExternalUsers.forEach(scvQyExternalUser -> {
                        if (scvSensorTenAggregationV2Vo.getExId().equals(scvQyExternalUser.getId())) {
                            scvSensorTenAggregationV2Vo.setAvatar(scvQyExternalUser.getAvatar());
                            scvSensorTenAggregationV2Vo.setNickName(scvQyExternalUser.getName());
                        }
                    });
                });
            }
            List<String> followerIdList = scvSensorTenAggregationV2Vos.stream().map(ScvSensorTenAggregationV2Vo::getFollowUserId)
                    .collect(Collectors.toList());
            List<ScvSourceQyQyUsers> list = scvSourceQyQyUsersService.list(new LambdaQueryWrapper<ScvSourceQyQyUsers>().eq(ScvSourceQyQyUsers::getQyId, actionsDto.getQyId()).in(ScvSourceQyQyUsers::getUserid, followerIdList));
            //企业微信员工属性赋值
            scvSensorTenAggregationV2Vos.forEach(scvSensorTenAggregationV2Vo -> {
                list.forEach(scvSourceQyQyUsers -> {
                    if (scvSourceQyQyUsers.getUserid().equals(scvSensorTenAggregationV2Vo.getFollowUserId())) {
                        scvSensorTenAggregationV2Vo.setFollowUserName(scvSourceQyQyUsers.getName());
                        if (StringUtils.isNotBlank(scvSourceQyQyUsers.getMobile())) {
                            scvSensorTenAggregationV2Vo.setMobile(AesUtils.desEncryptTerminal(scvSourceQyQyUsers.getMobile()));
                        }
                    }
                });
            });
            List<String> userCodeList = scvSensorTenAggregationV2Vos.stream().map(ScvSensorTenAggregationV2Vo::getUserCode).collect(Collectors.toList());
            List<SysUser> list1 = sysUserService.list(new LambdaQueryWrapper<SysUser>().in(SysUser::getUserLogin, userCodeList));
            scvSensorTenAggregationV2Vos.forEach(scvUserLiveRoomBehaviorVo -> {
                list1.forEach(sysUser -> {
                    if(scvUserLiveRoomBehaviorVo.getUserCode().equals(sysUser.getUserLogin())){
                        scvUserLiveRoomBehaviorVo.setName(sysUser.getRealname());
                    }
                });
            });
        }
        return ResultJson.success(new PageInfo<>(scvSensorTenAggregationV2Vos));
    }

    @Override
    public ResultJson getWebWxGpLiveInfo(ActionsDto actionsDto) {
        PageHelper.startPage(actionsDto.getPageNum(), actionsDto.getPageSize());
        List<ScvWxSensorTenAggregationV2Vo> scvSensorTenAggregationV2Vos = scvSensorTenAggregationMapper.getWebWxGpLiveList(actionsDto);
        if (!CollectionUtils.isEmpty(scvSensorTenAggregationV2Vos)) {

            //通过customerWxid获取客户的信息赋值到列表vo
            List<String> collectCustomerWxid = scvSensorTenAggregationV2Vos.stream().map(ScvWxSensorTenAggregationV2Vo::getCustomerWxid)
                    .collect(Collectors.toList());
            //通过customerWxid集合获取customer_wechat_detail客户微信表的详情信息
            List<CustomerWechatDetail> customerWechatDetailUsers = customerWechatDetailService.listByCustomerWxid(collectCustomerWxid);

            //客户信息赋值
            if (!CollectionUtils.isEmpty(customerWechatDetailUsers)) {
                scvSensorTenAggregationV2Vos.forEach(scvUserLiveRoomBehaviorVo -> {
                    customerWechatDetailUsers.forEach(customerWechatDetailUser -> {
                        if (scvUserLiveRoomBehaviorVo.getCustomerWxid().equals(customerWechatDetailUser.getCustomerWxid())) {
                            scvUserLiveRoomBehaviorVo.setAvatar(customerWechatDetailUser.getWechatHeadUrl());
                            scvUserLiveRoomBehaviorVo.setNickName(customerWechatDetailUser.getNickname());
                        }
                    });
                });
            }

            //获取微信号-company_wxid在customer_wechat_detail中关联user_id然后获取wechat_wxacc
            List<String> collectCompanyWxid = scvSensorTenAggregationV2Vos.stream().map(ScvWxSensorTenAggregationV2Vo::getCustomerWxid)
                    .collect(Collectors.toList());

            //通过customerWxid集合获取customer_wechat_detail客户微信表的详情信息
            List<CustomerWechatDetail> companyCustomerWechatDetailUsers = customerWechatDetailService.listByCustomerWxid(collectCompanyWxid);
            //所属微信号赋值
            scvSensorTenAggregationV2Vos.forEach(scvFwwechatUserBehaviorVo -> {
                companyCustomerWechatDetailUsers.forEach(companyCustomerWechatDetailUser -> {
                    if(scvFwwechatUserBehaviorVo.getCompanyWxid()!=null){
                        if (scvFwwechatUserBehaviorVo.getCompanyWxid().equals(companyCustomerWechatDetailUser.getCustomerWxid())) {
                            if (StringUtils.isNotBlank(companyCustomerWechatDetailUser.getWechatWxacc())) {
                                scvFwwechatUserBehaviorVo.setBelongWxid(AesUtils.decrypt(companyCustomerWechatDetailUser.getWechatWxacc(), secretKey));
                            }
                        }
                    }
                });
            });
        }
        return ResultJson.success(new PageInfo<>(scvSensorTenAggregationV2Vos));
    }

    @Override
    public ResultJson getWebWeChatGpLiveInfoV2(ActionsDto actionsDto) {

        PageHelper.startPage(actionsDto.getPageNum(), actionsDto.getPageSize());
        List<ScvSensorTenAggregationV2Vo> scvSensorTenAggregationV2Vos = scvSensorTenAggregationV2Mapper.getWebWeChatGpLiveList(actionsDto);
        if (!CollectionUtils.isEmpty(scvSensorTenAggregationV2Vos)) {
            //外部联系人id
            List<Integer> collect = scvSensorTenAggregationV2Vos.stream().map(ScvSensorTenAggregationV2Vo::getExId)
                    .collect(Collectors.toList());
            List<ScvQyExternalUser> scvQyExternalUsers = scvQyExternalUserService.listByExternalId(collect);
            //外部联系人属性赋值
            if (!CollectionUtils.isEmpty(scvQyExternalUsers)) {
                scvSensorTenAggregationV2Vos.forEach(scvSensorTenAggregationV2Vo -> {
                    scvQyExternalUsers.forEach(scvQyExternalUser -> {
                        if (scvSensorTenAggregationV2Vo.getExId().equals(scvQyExternalUser.getId())) {
                            scvSensorTenAggregationV2Vo.setAvatar(scvQyExternalUser.getAvatar());
                            scvSensorTenAggregationV2Vo.setNickName(scvQyExternalUser.getName());
                        }
                    });
                });
            }
            List<String> followerIdList = scvSensorTenAggregationV2Vos.stream().map(ScvSensorTenAggregationV2Vo::getFollowUserId)
                    .collect(Collectors.toList());
            List<ScvSourceQyQyUsers> list = scvSourceQyQyUsersService.list(new LambdaQueryWrapper<ScvSourceQyQyUsers>().eq(ScvSourceQyQyUsers::getQyId, actionsDto.getQyId()).in(ScvSourceQyQyUsers::getUserid, followerIdList));
            //企业微信员工属性赋值
            scvSensorTenAggregationV2Vos.forEach(scvSensorTenAggregationV2Vo -> {
                list.forEach(scvSourceQyQyUsers -> {
                    if (scvSourceQyQyUsers.getUserid().equals(scvSensorTenAggregationV2Vo.getFollowUserId())) {
                        scvSensorTenAggregationV2Vo.setFollowUserName(scvSourceQyQyUsers.getName());
                        if (StringUtils.isNotBlank(scvSourceQyQyUsers.getMobile())) {
                            scvSensorTenAggregationV2Vo.setMobile(AesUtils.desEncryptTerminal(scvSourceQyQyUsers.getMobile()));
                        }
                    }
                });
            });
            List<String> userCodeList = scvSensorTenAggregationV2Vos.stream().map(ScvSensorTenAggregationV2Vo::getUserCode).collect(Collectors.toList());
            List<SysUser> list1 = sysUserService.list(new LambdaQueryWrapper<SysUser>().in(SysUser::getUserLogin, userCodeList));
            scvSensorTenAggregationV2Vos.forEach(scvUserLiveRoomBehaviorVo -> {
                list1.forEach(sysUser -> {
                    if(scvUserLiveRoomBehaviorVo.getUserCode().equals(sysUser.getUserLogin())){
                        scvUserLiveRoomBehaviorVo.setName(sysUser.getRealname());
                    }
                });
            });
        }
        return ResultJson.success(new PageInfo<>(scvSensorTenAggregationV2Vos));

    }

    @Override
    public ResultJson getWebWxGpLiveInfoV2(ActionsDto actionsDto) {

        PageHelper.startPage(actionsDto.getPageNum(), actionsDto.getPageSize());
        List<ScvWxSensorTenAggregationV2Vo> scvSensorTenAggregationV2Vos = scvSensorTenAggregationV2Mapper.getWebWxGpLiveList(actionsDto);
        if (!CollectionUtils.isEmpty(scvSensorTenAggregationV2Vos)) {

            //通过customerWxid获取客户的信息赋值到列表vo
            List<String> collectCustomerWxid = scvSensorTenAggregationV2Vos.stream().map(ScvWxSensorTenAggregationV2Vo::getCustomerWxid)
                    .collect(Collectors.toList());
            //通过customerWxid集合获取customer_wechat_detail客户微信表的详情信息
            List<CustomerWechatDetail> customerWechatDetailUsers = customerWechatDetailService.listByCustomerWxid(collectCustomerWxid);

            //客户信息赋值
            if (!CollectionUtils.isEmpty(customerWechatDetailUsers)) {
                scvSensorTenAggregationV2Vos.forEach(scvUserLiveRoomBehaviorVo -> {
                    customerWechatDetailUsers.forEach(customerWechatDetailUser -> {
                        if (scvUserLiveRoomBehaviorVo.getCustomerWxid().equals(customerWechatDetailUser.getCustomerWxid())) {
                            scvUserLiveRoomBehaviorVo.setAvatar(customerWechatDetailUser.getWechatHeadUrl());
                            scvUserLiveRoomBehaviorVo.setNickName(customerWechatDetailUser.getNickname());
                        }
                    });
                });
            }

            //获取微信号-company_wxid在customer_wechat_detail中关联user_id然后获取wechat_wxacc
            List<String> collectCompanyWxid = scvSensorTenAggregationV2Vos.stream().map(ScvWxSensorTenAggregationV2Vo::getCustomerWxid)
                    .collect(Collectors.toList());

            //通过customerWxid集合获取customer_wechat_detail客户微信表的详情信息
            List<CustomerWechatDetail> companyCustomerWechatDetailUsers = customerWechatDetailService.listByCustomerWxid(collectCompanyWxid);
            //所属微信号赋值
            scvSensorTenAggregationV2Vos.forEach(scvFwwechatUserBehaviorVo -> {
                companyCustomerWechatDetailUsers.forEach(companyCustomerWechatDetailUser -> {
                    if(scvFwwechatUserBehaviorVo.getCompanyWxid()!=null){
                        if (scvFwwechatUserBehaviorVo.getCompanyWxid().equals(companyCustomerWechatDetailUser.getCustomerWxid())) {
                            if (StringUtils.isNotBlank(companyCustomerWechatDetailUser.getWechatWxacc())) {
                                scvFwwechatUserBehaviorVo.setBelongWxid(AesUtils.decrypt(companyCustomerWechatDetailUser.getWechatWxacc(), secretKey));
                            }
                        }
                    }
                });
            });
        }
        return ResultJson.success(new PageInfo<>(scvSensorTenAggregationV2Vos));

    }
}
